#!/bin/bash
# hostguard: Startup script for hostguard (Huawei Host Security Agent)
#
# chkconfig: 2345 12 88
# description: hostguard, Huawei Host Security Agent
 
### BEGIN INIT INFO
# Provides:          hostguard
# Required-Start:    $local_fs
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Huawei Host Security Agent
# Description:       protect your host from intrusions.
### END INIT INFO
 
HOSTGUARD_INSTALL_DIR="/usr/local/hostguard"
LOG_PATH="/usr/local/hostguard/log"
PIDFile="${HOSTGUARD_INSTALL_DIR}/bin/hostguard.pid"
 
if [ `id -u` -ne "0" ]; then
    echo "ERROR: Permission denied." 1>&2
    exit 1
fi
 
if [ $# == 2 ]; then
    if [ "$2" != ${LOG_PATH} ]; then
        mkdir -p "$2"
    fi
    LOG_PATH=$2
fi
 
check_descape_killed()
{
    n=0
    while true
    do
        if [ -n "$(pgrep descape)" ]; then
            exitprocess=$(pgrep descape)
            if [ ${exitprocess} -ne 0 ] ; then
                sleep 1
            else
                break
            fi
            let n++
            if [ $n -gt 10 ] ; then
                kill -9 ${exitprocess}
                break
            fi
        else
            break
        fi
    done
}
 
start() {
	 "${HOSTGUARD_INSTALL_DIR}"/bin/hostguard 
}
 
stop() {
    echo "Stopping Hostguard..."
    kill -QUIT $(cat "${HOSTGUARD_INSTALL_DIR}/bin/hostguard.pid" 2>/dev/null) 2>/dev/null
    sleep 7
    check_descape_killed

    if [ -f /usr/local/hostguard/bin/hostguard.pid ];then
        pid=$(cat /usr/local/hostguard/bin/hostguard.pid)
        if [ ! -z "$pid" -a "$pid"x != "1"x -a -f /proc/$pid/cmdline ];then
            ret=$(echo `cat /proc/$pid/cmdline` | grep '/usr/local/hostguard/bin/hostguard')
            if [ -n "$ret" ];then
                kill -9 -${pid} >/dev/null 2>/dev/null
                sleep 2
            fi
        fi
    fi

    program=$(ps -ef | grep '/usr/local/hostguard' |grep -E -v 'grep|conf|lib|log|\.sh|\.pid|\.so'|awk '{print $2}')
    if [ -n "$program" ]; then
        kill -9 ${program} >/dev/null 2>/dev/null
        sleep 2
    fi
    status
}
 
status() {
	if [ -n "$(ps -ef | grep '/usr/local/hostguard' | grep -v grep | grep -v '/etc/init.d/hostguard' | grep -v 'service'|grep -v 'rpm'|grep -v 'systemctl'|grep -v 'dpkg' | grep -v 'defunct')" ]; then
		echo "Hostguard is running"
	else
		echo "Hostguard stopped"
	fi
}
 
 
case "$1" in
    start)
        start ${LOG_PATH} 
        sleep 1
        status
    ;;
 
    stop)
        stop
    ;;
 
    restart)
        stop
        echo "Hostguard restarting..."
        sleep 1
        start ${LOG_PATH}
        status
    ;;
 
    status)
        status
    ;;
 
    *)
        echo $"Usage: $0 {start [log path]|stop|restart [log path]|status}"
        exit 1
    ;;
 
esac
